package org.goldfish.distributed_framework.client;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * RpcInvoker
 * 负责发送RpcRequest并接收RpcResponse
 */
public class RpcInvoker {

    /**
     * 远程调用服务方法
     *
     * @param address 远程服务地址，格式为"host:port"
     * @param request RpcRequest对象
     * @return RpcResponse对象
     * @throws Exception 网络通信或序列化/反序列化异常
     */
    public static RpcResponse invoke(String address, RpcRequest request) throws Exception {
        String[] parts = address.split(":");
        String host = parts[0];
        int port = Integer.parseInt(parts[1]);
        System.out.println("调用服务: " + address);
        try (Socket socket = new Socket(host, port);
             ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
            socket.setSoTimeout(600 * 1000);

            System.out.println("发送请求: " + request);
            out.writeObject(request);
            out.flush();
            System.out.println("等待响应");

            Object response = in.readObject();
            System.out.println("接收响应: " + response);
            if (response instanceof RpcResponse) {
                return (RpcResponse) response;
            } else {
                throw new RuntimeException("Invalid response from server: " + response);
            }
        }
    }
}
